package com.laiketui.app.services.dubbo.bargain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.laiketui.app.api.bargain.BargainService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.api.plugin.PubliceBargainService;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.core.utils.tool.DateUtil;
import com.laiketui.core.utils.tool.SerializePhpUtils;
import com.laiketui.domain.config.ConfiGureModel;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.order.BargainOrderModel;
import com.laiketui.domain.order.OrderModel;
import com.laiketui.domain.plugin.bargain.BargainConfigModel;
import com.laiketui.domain.plugin.bargain.BargainRecordModel;
import com.laiketui.domain.product.BargainGoodsModel;
import com.laiketui.domain.product.ProductListModel;
import com.laiketui.domain.product.StockModel;
import com.laiketui.domain.user.User;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.root.common.BuilderIDTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;

/**
 * 砍价实现
 *
 * @author Trick
 * @date 2021/4/16 15:16
 */
@Service
public class BargainServiceImpl implements BargainService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BargainGoodsModelMapper bargainGoodsModelMapper;

    @Autowired
    private BargainConfigModelMapper bargainConfigModelMapper;

    @Autowired
    private PubliceBargainService publiceBargainService;

    @Autowired
    private BargainOrderModelMapper bargainOrderModelMapper;

    @Autowired
    private ProductListModelMapper productListModelMapper;

    @Autowired
    private ConfiGureModelMapper confiGureModelMapper;

    @Autowired
    private BargainRecordModelMapper bargainRecordModelMapper;

    @Autowired
    private StockModelMapper stockModelMapper;

    @Autowired
    private OrderModelMapper orderModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Map<String, Object> getBargainGoodsList(MainVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil);
            //结束已经到期的活动
            int row = bargainGoodsModelMapper.clearBargainByEnd(new Date());
            //获取砍价配置信息
            BargainConfigModel bargainConfigModel = new BargainConfigModel();
            bargainConfigModel.setStore_id(vo.getStoreId());
            bargainConfigModel = bargainConfigModelMapper.selectOne(bargainConfigModel);
            if (bargainConfigModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KJPZBCZ, "砍价配置不存在");
            }
            resultMap.put("list", publiceBargainService.bargainGoodsInfo(vo.getStoreId(), vo.getPageNo(), vo.getPageSize(), user));
            resultMap.put("img", bargainConfigModel.getImgurl());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取砍价商品列表 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getBargainGoodsList");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> mybargain(MainVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
            //结束已经到期的活动
            bargainGoodsModelMapper.clearBargainByEnd(new Date());
            //获取用户参与的砍价活动
            List<Map<String, Object>> bargainList = bargainOrderModelMapper.getUserBargainList(user.getUser_id(), vo.getPageNo(), vo.getPageSize());

            for (Map<String, Object> bargain : bargainList) {
                //砍价商品id
                int bargainId = Integer.parseInt(bargain.get("bargain_id").toString());
                //订单状态
                int orderStatus = Integer.parseInt(bargain.get("status").toString());
                //订单号
                String barginOrderno = bargain.get("order_no").toString();
                //商品id
                int goodsId = Integer.parseInt(bargain.get("goods_id").toString());
                //商品属性id
                int attrId = Integer.parseInt(bargain.get("attr_id").toString());
                //倒计时
                long leftTime;
                BargainGoodsModel bargainGoodsModel = bargainGoodsModelMapper.selectByPrimaryKey(bargainId);
                Date endDate = DateUtil.dateFormateToDate(bargainGoodsModel.getEnd_time(), GloabConst.TimePattern.YMDHMS);
                if (endDate == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
                }
                leftTime = endDate.getTime() / 1000 - DateUtil.getTime();
                //获取砍价配置信息
                BargainConfigModel bargainConfigModel = new BargainConfigModel();
                bargainConfigModel.setStore_id(vo.getStoreId());
                bargainConfigModel = bargainConfigModelMapper.selectOne(bargainConfigModel);
                if (bargainConfigModel == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
                }

                //获取商品信息
                ProductListModel productListModel = productListModelMapper.selectByPrimaryKey(goodsId);
                if (productListModel == null) {
                    bargain.put("title", "商品被删掉了");
                } else {
                    bargain.put("title", productListModel.getProduct_title());
                }
                //获取商品属性信息
                ConfiGureModel confiGureModel = confiGureModelMapper.selectByPrimaryKey(attrId);
                bargain.put("img", publiceService.getImgPath(confiGureModel.getImg(), vo.getStoreId()));
                bargain.put("price", confiGureModel.getPrice());
                //计算一共砍了多少钱
                BigDecimal orderAmt = bargainRecordModelMapper.getOrderMoney(vo.getStoreId(), barginOrderno);
                bargain.put("success_money", orderAmt);
                //获取订单信息
                OrderModel orderModel = orderModelMapper.getNotCloseOrdersByNo(barginOrderno);
                //前端倒计时初始化
                bargain.put("hour","00");
                bargain.put("mniuate","00");
                bargain.put("second","00");
                //-1/-2.砍价失败 0.未开始砍价 1.砍价中 2.砍价成功 3.已付款
                int status = -2;
                if (orderStatus == 0) {
                    status = 1;
                } else if (orderStatus == 1) {
                    //砍价成功
                    status = 2;
                    // 砍价成功，支付限制时间 /小时
                    Integer buyTime = bargainConfigModel.getBuy_time();
                    // 后台设置结算时间大于0时
                    if (buyTime != null && buyTime > 0) {
                        //砍价成功时间
                        long achievetime = Long.parseLong(bargain.get("achievetime").toString());
                        achievetime += DateUtil.dateConversion(buyTime, DateUtil.TimeType.TIME);
                        // 购买时间 = 截止时间-当前时间
                        bargain.put("canbuy", achievetime - DateUtil.getTime());
                    } else {
                        // 购买时间 = 活动剩余时间 并刷新时间
                        bargain.put("canbuy", leftTime = endDate.getTime() / 1000 - DateUtil.getTime());
                    }
                    if (leftTime > 0) {
                        if (orderModel != null) {
                            //如果订单已创建
                            bargain.put("hasorder", 1);
                            bargain.put("sNo_id", orderModel.getId());
                            if (orderModel.getStatus().equals(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID)) {
                                bargain.put("gopay", 1);
                            } else {
                                status = 3;
                            }
                        }
                    } else {
                        status = -1;
                    }
                }
                bargain.put("isbegin", 1);
                bargain.put("status", status);
                bargain.put("leftTime", leftTime);
            }
            resultMap.put("list", bargainList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取我的砍价列表 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getBargainGoodsList");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getRule(MainVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            BargainConfigModel bargainConfigModel = new BargainConfigModel();
            bargainConfigModel.setStore_id(vo.getStoreId());
            bargainConfigModel = bargainConfigModelMapper.selectOne(bargainConfigModel);
            resultMap.put("rule", bargainConfigModel.getRule());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取砍价规则 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getRule");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> createbargain(MainVo vo, int bargainId) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            int count;
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
            //获取商品信息
            BargainGoodsModel bargainGoodsModel = bargainGoodsModelMapper.selectByPrimaryKey(bargainId);
            if (bargainGoodsModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KJSPBCZ, "砍价商品不存在");
            }
            //获取商品属性信息
            ConfiGureModel confiGureModel = confiGureModelMapper.selectByPrimaryKey(bargainGoodsModel.getAttr_id());
            if (confiGureModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPSXXXBCZ, "商品属性信息不存在");
            }
            if (confiGureModel.getNum() < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPKCBZ, "商品库存不足");
            }
            //砍价参数  O:8:"stdClass":3:{s:7:"one_man";s:1:"1";s:7:"min_one/min_not";s:3:"100";s:7:"max_one";s:4:"2000";}
            Map<String, Object> bargainParmaMap = DataUtils.cast(SerializePhpUtils.getUnserializeObj(bargainGoodsModel.getStatus_data(), Map.class));
            if (bargainParmaMap == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            //好友砍价列表
            List<Map<String, Object>> friendBargainList;
            //砍价详情
            Map<String, Object> bargainOrderMap;
            //生成订单号
            String bargainOrderno = DictionaryConst.OrdersType.ORDERS_HEADER_KJ + BuilderIDTool.getNext(BuilderIDTool.Type.NUMBER, 10);
            //砍价人数如果没有限制,则随机砍价。如果设置了人数，根据参数进行砍价
            BigDecimal min;
            BigDecimal max;
            BigDecimal num = new BigDecimal("10");
            //砍价金额
            BigDecimal kanPrice;
            if (bargainGoodsModel.getMan_num() == 0) {
                //人数无限制,一直随机砍到最低
                min = new BigDecimal(bargainParmaMap.get("min_not").toString()).multiply(num);
                max = new BigDecimal(bargainParmaMap.get("max_not").toString()).multiply(num);
            } else {
                min = new BigDecimal(bargainParmaMap.get("min_one").toString()).multiply(num);
                max = new BigDecimal(bargainParmaMap.get("max_one").toString()).multiply(num);
            }
            //随机值
            kanPrice = new BigDecimal(DataUtils.random(min.doubleValue(), max.doubleValue()) + "");
            //剩余价格 = 商品原价-最低价格-自己砍价金额
            BigDecimal originalPrice = confiGureModel.getPrice().subtract(bargainGoodsModel.getMin_price()).subtract(kanPrice);

            //查询订单是否存在
            BargainOrderModel bargainOrderModel = new BargainOrderModel();
            bargainOrderModel.setStore_id(vo.getStoreId());
            bargainOrderModel.setUser_id(user.getUser_id());
            bargainOrderModel.setAttr_id(confiGureModel.getId());
            bargainOrderModel.setBargain_id(bargainId);
            bargainOrderModel.setGoods_id(confiGureModel.getPid());
            BargainOrderModel bargainOrderTemp = bargainOrderModelMapper.selectOne(bargainOrderModel);
            if (bargainOrderTemp == null) {
                //添加砍价订单
                bargainOrderModel.setOrder_no(bargainOrderno);
                bargainOrderModel.setOriginal_price(originalPrice);
                bargainOrderModel.setMin_price(bargainGoodsModel.getMin_price());
                bargainOrderModel.setAddtime(Integer.parseInt(DateUtil.getTime() + ""));
                bargainOrderModel.setStatus_data(bargainGoodsModel.getStatus_data());
                bargainOrderModel.setBargain_id(bargainGoodsModel.getId());
                count = bargainOrderModelMapper.insertSelective(bargainOrderModel);
                if (count < 1) {
                    logger.error("砍价订单创建失败");
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSYC, "参数异常");
                }
                //生成一条砍价记录
                BargainRecordModel bargainRecordSave = new BargainRecordModel();
                bargainRecordSave.setStore_id(vo.getStoreId());
                bargainRecordSave.setOrder_no(bargainOrderno);
                bargainRecordSave.setUser_id(user.getUser_id());
                bargainRecordSave.setMoney(kanPrice.setScale(2, BigDecimal.ROUND_FLOOR));
                bargainRecordSave.setAdd_time(DateUtil.getTime() + "");
                count = bargainRecordModelMapper.insertSelective(bargainRecordSave);
                if (count < 1) {
                    logger.error("砍价记录添加失败");
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSYC, "参数异常");
                }
                //扣减库存
                count = confiGureModelMapper.reduceGoodsStockNum(-1, confiGureModel.getId());
                if (count < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPKCBZ, "商品库存不足");
                }
                //生成出库日志
                String textLogo = "%s生成订单所需%s";
                StockModel stockModel = new StockModel();
                stockModel.setStore_id(vo.getStoreId());
                stockModel.setProduct_id(confiGureModel.getPid());
                stockModel.setAttribute_id(confiGureModel.getId());
                stockModel.setTotal_num(confiGureModel.getNum());
                stockModel.setFlowing_num(1);
                stockModel.setUser_id(user.getUser_id());
                stockModel.setContent(textLogo);
                stockModel.setAdd_date(new Date());
                stockModelMapper.insertSelective(stockModel);
                bargainOrderModel = bargainOrderModelMapper.selectByPrimaryKey(bargainOrderModel.getId());
                //帮砍金额
                resultMap.put("bargain_money", kanPrice);
            } else {
                bargainOrderModel = bargainOrderTemp;
                bargainOrderno = bargainOrderModel.getOrder_no();
                //不弹砍价成功窗口
                resultMap.put("status", 500);
            }
            //帮好友砍价
            friendBargainList = bargainRecordModelMapper.getFriendBargainList(vo.getStoreId(), bargainOrderno);
            //获取商品名称
            ProductListModel productListModel = productListModelMapper.selectByPrimaryKey(bargainGoodsModel.getGoods_id());
            if (productListModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在");
            }
            bargainOrderMap = JSON.parseObject(JSON.toJSONString(bargainOrderModel), new TypeReference<Map<String, Object>>() {
            });
            bargainOrderMap.put("title", productListModel.getProduct_title());
            bargainOrderMap.put("price", confiGureModel.getPrice());
            bargainOrderMap.put("img", publiceService.getImgPath(confiGureModel.getImg(), vo.getStoreId()));
            bargainOrderMap.put("leftTime", Objects.requireNonNull(DateUtil.dateFormateToDate(bargainGoodsModel.getEnd_time(), GloabConst.TimePattern.YMDHMS)).getTime() / 1000 - DateUtil.getTime());
            bargainOrderMap.put("bargain_id", bargainGoodsModel.getId());
            //获取总砍价金额
            bargainOrderMap.put("success_money", bargainRecordModelMapper.getOrderMoney(vo.getStoreId(), bargainOrderno).setScale(2, BigDecimal.ROUND_FLOOR));
            //需砍金额
            bargainOrderMap.put("free_money", bargainOrderModel.getOriginal_price().setScale(2, BigDecimal.ROUND_FLOOR));

            resultMap.put("order_no", bargainOrderno);
            resultMap.put("list", bargainOrderMap);
            resultMap.put("loseEfficacy", false);
            resultMap.put("min_price", bargainGoodsModel.getMin_price());
            resultMap.put("help_list", friendBargainList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("立即砍价 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "createbargain");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getgoodsdetail(MainVo vo, String orderno) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil);
            Map<String, Object> userMap = new HashMap<>(16);
            int isLogin = 1;
            if (user == null) {
                isLogin = 0;
            } else {
                userMap.put("user_name", user.getUser_name());
                userMap.put("headimgurl", user.getHeadimgurl());
            }
            int isMyShareLink = 0;
            //获取砍价订单信息
            BargainOrderModel bargainOrderModel = new BargainOrderModel();
            bargainOrderModel.setStore_id(vo.getStoreId());
            bargainOrderModel.setOrder_no(orderno);
            bargainOrderModel = bargainOrderModelMapper.selectOne(bargainOrderModel);
            if (bargainOrderModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KJDDBCZ, "砍价订单不存在");
            } else {
                if (user != null) {
                    //是否是自己发起的砍价
                    if (bargainOrderModel.getUser_id().equals(user.getUser_id())) {
                        isMyShareLink = 1;
                    }
                }
            }
            resultMap.putAll(getList(bargainOrderModel, user));
            //帮好友砍价列表
            List<Map<String, Object>> friendBargainList = new ArrayList<>();
            if (user != null) {
                friendBargainList = bargainRecordModelMapper.getFriendBargainList(vo.getStoreId(), orderno);
            }
            //发起砍价的用户信息
            resultMap.put("self", userMap);
            //是否是自己发起的砍价
            resultMap.put("isMyShareLink", isMyShareLink);
            //好友帮砍明细
            resultMap.put("help_list", friendBargainList);
            //活动是否失效
            resultMap.put("loseEfficacy", false);
            resultMap.put("islogin", isLogin);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取当前砍价商品详情 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getgoodsdetail");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> helpbargain(MainVo vo, String orderno) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
            //获取砍价订单信息
            Map<String, Object> bargainOrderMap = new HashMap<>(16);
            BargainOrderModel bargainOrderModel = new BargainOrderModel();
            bargainOrderModel.setStore_id(vo.getStoreId());
            bargainOrderModel.setOrder_no(orderno);
            bargainOrderModel = bargainOrderModelMapper.selectOne(bargainOrderModel);
            if (bargainOrderModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KJDDBCZ, "砍价订单不存在");
            }
            bargainOrderMap = getList(bargainOrderModel, user);
            //好友砍价列表
            List<Map<String, Object>> friendBargainList = bargainRecordModelMapper.getFriendBargainList(vo.getStoreId(), orderno);
            //此人是否已经对同一个订单已经砍过价
            if (bargainOrderMap.containsKey("status") && "500".equals(bargainOrderMap.get("status"))) {
                //已经砍过
                resultMap.putAll(bargainOrderMap);
                resultMap.put("help_list", friendBargainList);
                resultMap.put("statusCode", 500);
                return resultMap;
            }
            //获取砍价商品信息
            BargainGoodsModel bargainGoodsModel = bargainGoodsModelMapper.selectByPrimaryKey(bargainOrderModel.getBargain_id());
            //获取砍价配置参数  O:8:"stdClass":3:{s:7:"one_man";s:1:"1";s:7:"min_one/min_not";s:3:"100";s:7:"max_one";s:4:"2000";}
            Map<String, Object> bargainParmaMap = DataUtils.cast(SerializePhpUtils.getUnserializeObj(bargainGoodsModel.getStatus_data(), Map.class));
            if (bargainParmaMap == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            //获取已砍人数
            BargainRecordModel bargainRecordModel = new BargainRecordModel();
            bargainRecordModel.setStore_id(vo.getStoreId());
            bargainRecordModel.setOrder_no(orderno);
            int helpNum = bargainRecordModelMapper.selectCount(bargainRecordModel);
            //状态标识
            String status = "";
            //砍价人数如果没有限制,则随机砍价。如果设置了人数，根据参数进行砍价
            BigDecimal min;
            BigDecimal max;
            //砍价金额
            BigDecimal kanPrice;
            //剩余金额
            BigDecimal originalPrice = bargainOrderModel.getOriginal_price();
            if (bargainParmaMap.containsKey("min_not") && bargainParmaMap.containsKey("max_not")) {
                //人数无限制,一直随机砍到最低
                min = new BigDecimal(bargainParmaMap.get("min_not").toString());
                max = new BigDecimal(bargainParmaMap.get("max_not").toString());
            } else if (Integer.parseInt(bargainParmaMap.get("one_man").toString()) <= helpNum) {
                //限制了人数而且已经达到第一批人数
                min = originalPrice;
                max = new BigDecimal("0.01");
            } else {
                //限制了人数，人数没达到第一批人数
                min = new BigDecimal(bargainParmaMap.get("min_one").toString());
                max = new BigDecimal(bargainParmaMap.get("max_one").toString());
            }
            //是否限制砍价人数
            if (bargainGoodsModel.getMan_num() == 0) {
                //无限制 剩余金额>=最低金额
                if (originalPrice.compareTo(min) >= 0) {
                    if (max.compareTo(originalPrice) > 0) {
                        //最大取值范围
                        max = originalPrice;
                    }
                    //随机值
                    kanPrice = new BigDecimal(DataUtils.random(min.doubleValue(), max.doubleValue()) + "");
                } else {
                    //如果最低范围大于剩余金额,直接砍价成功ba
                    kanPrice = originalPrice;
                }
                if (kanPrice.compareTo(originalPrice) >= 0) {
                    //砍价完成
                    kanPrice = originalPrice;
                    status = "success";
                    int count = bargainOrderModelMapper.bargainSuccess(vo.getStoreId(), orderno, DateUtil.getTime());
                    if (count < 1) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KJSB, "砍价失败");
                    }
                } else {
                    //帮砍成功
                    int count = bargainOrderModelMapper.updateOriginalPrice(vo.getStoreId(), orderno, kanPrice, DateUtil.getTime());
                    if (count < 1) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KJSB, "砍价失败");
                    }
                }
            } else {
                //有人数限制
                int oneMan = Integer.parseInt(bargainParmaMap.get("one_man").toString());
                //还剩余多砍价名额
                int shenManNum = bargainGoodsModel.getMan_num() - helpNum;
                //下一波剩余多少人
                int twoman = bargainGoodsModel.getMan_num() - oneMan;
                //是否在第一波人里面
                if (oneMan > helpNum) {
                    min = new BigDecimal(bargainParmaMap.get("min_one").toString());
                    //第一波还有多少人没砍
                    int oneNeed = shenManNum - twoman;
                    //计算第二波没人砍0.01,第一批最多还能砍多少
                    BigDecimal onecan = originalPrice.subtract(new BigDecimal(twoman + "").multiply(new BigDecimal("0.01")));
                    //计算第一波人每人砍最低价，这个人可以砍多少
                    max = onecan.subtract(new BigDecimal(oneNeed + "").multiply(min));
                    //判断是否超过后台剩余价格,如果超过则设置为剩余价格
                    if (max.compareTo(new BigDecimal(bargainParmaMap.get("max_one").toString())) >= 0) {
                        max = originalPrice;
                    }
                } else {
                    //在第二波人内
                    if (shenManNum > 1) {
                        min = new BigDecimal("0.01");
                        max = originalPrice.subtract(new BigDecimal(twoman + ""));
                    } else {
                        min = max = originalPrice;
                    }
                }
                if (shenManNum > 1) {
                    //如果不是最后一个人
                    kanPrice = new BigDecimal(DataUtils.random(min.doubleValue(), max.doubleValue()));
                    //帮砍成功
                    int count = bargainOrderModelMapper.updateOriginalPrice(vo.getStoreId(), orderno, kanPrice, DateUtil.getTime());
                    if (count < 1) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KJSB, "砍价失败");
                    }
                } else {
                    //砍价完成
                    kanPrice = originalPrice;
                    status = "success";
                    int count = bargainOrderModelMapper.bargainSuccess(vo.getStoreId(), orderno, DateUtil.getTime());
                    if (count < 1) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KJSB, "砍价失败");
                    }
                }
            }
            //添加砍价记录
            bargainRecordModel.setStore_id(vo.getStoreId());
            bargainRecordModel.setOrder_no(orderno);
            bargainRecordModel.setUser_id(user.getUser_id());
            bargainRecordModel.setMoney(kanPrice);
            bargainRecordModel.setAdd_time(DateUtil.getTime() + "");
            int row = bargainRecordModelMapper.insertSelective(bargainRecordModel);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KJSB, "砍价失败");
            }
            resultMap.putAll(bargainOrderMap);
            resultMap.put("status", status);
            resultMap.put("statusCode", 200);
            resultMap.put("user_name", user.getUser_name());
            resultMap.put("headimgurl", user.getHeadimgurl());
            resultMap.put("help_list", friendBargainList);
            resultMap.put("randprice", kanPrice);
        } catch (LaiKeAPIException l) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("好友帮砍 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "helpbargain");
        }
        return resultMap;
    }

    private Map<String, Object> getList(BargainOrderModel bargainOrderModel, User user) {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            //砍价详情
            Map<String, Object> bargainOrderMap = new HashMap<>(16);
            String status = "";
            if (bargainOrderModel != null) {
                if (bargainOrderModel.getId() != null) {
                    bargainOrderMap = JSON.parseObject(JSON.toJSONString(bargainOrderModel), new TypeReference<Map<String, Object>>() {
                    });
                    //获取商品名称
                    ProductListModel productListModel = productListModelMapper.selectByPrimaryKey(bargainOrderModel.getGoods_id());
                    if (productListModel == null) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在");
                    }
                    //获取商品属性信息
                    ConfiGureModel confiGureModel = confiGureModelMapper.selectByPrimaryKey(bargainOrderModel.getAttr_id());
                    if (confiGureModel == null) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPSXXXBCZ, "商品属性信息不存在");
                    }
                    if (confiGureModel.getNum() < 1) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPKCBZ, "商品库存不足");
                    }
                    //获取砍价活动信息
                    BargainGoodsModel bargainGoodsModel = bargainGoodsModelMapper.selectByPrimaryKey(bargainOrderModel.getBargain_id());
                    if (confiGureModel.getNum() < 1) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_HDBCZ, "活动不存在");
                    }
                    bargainOrderMap.put("loseEfficacy", bargainGoodsModel.getIs_show());
                    bargainOrderMap.put("title", productListModel.getProduct_title());
                    bargainOrderMap.put("price", confiGureModel.getPrice());
                    bargainOrderMap.put("stock_num", confiGureModel.getNum());
                    bargainOrderMap.put("img", publiceService.getImgPath(confiGureModel.getImg(), bargainOrderModel.getStore_id()));
                    bargainOrderMap.put("leftTime", Objects.requireNonNull(DateUtil.dateFormateToDate(bargainGoodsModel.getEnd_time(), GloabConst.TimePattern.YMDHMS)).getTime() / 1000 - DateUtil.getTime());
                    bargainOrderMap.put("bargain_id", bargainOrderModel.getBargain_id());
                    //获取总砍价金额
                    bargainOrderMap.put("success_money", bargainRecordModelMapper.getOrderMoney(bargainOrderModel.getStore_id(), bargainOrderModel.getOrder_no()).setScale(2, BigDecimal.ROUND_FLOOR));
                    //需砍金额
                    bargainOrderMap.put("free_money", bargainOrderModel.getOriginal_price().setScale(2, BigDecimal.ROUND_FLOOR));
                    //查询订单是否在总表创建 0.没创建 1.创建了
                    int hasorder = 0;
                    OrderModel orderModel = orderModelMapper.getNotCloseOrdersByNo(bargainOrderModel.getOrder_no());
                    if (orderModel != null) {
                        hasorder = 1;
                        bargainOrderMap.put("sNo_id", orderModel.getId());
                        //如果没付款,则提示付款
                        if (DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID == orderModel.getStatus()) {
                            bargainOrderMap.put("gopay", 1);
                        }
                    }
                    bargainOrderMap.put("hasorder", hasorder);
                }

                //selfstatus 0.进行中 1.待付款 2.已付款 3.失败 4.未参与
                int selfstatus = 0;
                if (user != null) {
                    //查询当前用户是否帮砍过
                    BargainRecordModel bargainRecordModel = new BargainRecordModel();
                    bargainRecordModel.setOrder_no(bargainOrderModel.getOrder_no());
                    bargainRecordModel.setUser_id(user.getUser_id());
                    int count = bargainRecordModelMapper.selectCount(bargainRecordModel);
                    if (count > 0) {
                        status = "500";
                    }
                    // 查询用户是否参与此砍价
                    BargainOrderModel bargainOrder = new BargainOrderModel();
                    bargainOrder.setStore_id(bargainOrderModel.getStore_id());
                    bargainOrder.setUser_id(bargainOrderModel.getUser_id());
                    bargainOrder.setBargain_id(bargainOrderModel.getBargain_id());
                    bargainOrderModel = bargainOrderModelMapper.selectOne(bargainOrder);
                    if (bargainOrderModel != null) {
                        int hasorder = 0;
                        OrderModel orderModel = orderModelMapper.getNotCloseOrdersByNo(bargainOrderModel.getOrder_no());
                        if (orderModel != null) {
                            hasorder = 1;
                        }
                        bargainOrderMap.put("selfhasorder", hasorder);
                        if (bargainOrderModel.getStatus() == 0) {
                            selfstatus = 1;
                            //查询砍价配置
                            BargainConfigModel bargainConfigModel = new BargainConfigModel();
                            bargainConfigModel.setStore_id(bargainOrderModel.getStore_id());
                            bargainConfigModel = bargainConfigModelMapper.selectOne(bargainConfigModel);
                            if (bargainConfigModel != null) {
                                if (bargainConfigModel.getBuy_time() > 0 && bargainOrderModel.getAchievetime() > 0) {
                                    //砍价成功,计算砍价成功到现在差多少秒
                                    int buyTime = DateUtil.dateConversion(bargainConfigModel.getBuy_time(), DateUtil.TimeType.TIME);
                                    long sysTime = DateUtil.getTime() - bargainOrderModel.getAchievetime();
                                    if (sysTime > buyTime) {
                                        // 如果距离时间大于购买时限 状态砍价失败
                                        selfstatus = 3;
                                    }
                                }
                            }
                        } else if (bargainOrderModel.getStatus() == 1) {
                            selfstatus = 2;
                        }
                    } else {
                        selfstatus = 4;
                    }
                } else {
                    selfstatus = 4;
                }
                bargainOrderMap.put("selfstatus", selfstatus);
            }
            resultMap.put("status", status);
            resultMap.put("list", bargainOrderMap);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("列表数据梳理 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getList");
        }
        return resultMap;
    }
}

